
package com.moji.controller.api;


import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.moji.common.config.AlipayConfig;
import com.moji.entity.MjOrder;
import com.moji.entity.MjOrderDetail;
import com.moji.service.MjOrderDetailService;
import com.moji.service.MjOrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/web/alipay")
@Slf4j
@Api(tags = "支付宝相关接口", value = "支付宝相关接口")
public class AlipayController {

    @Autowired
    private MjOrderService orderService;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private MjOrderDetailService mjOrderDetailService;
    /**
     * alipayConfig
     * 微信开放平台二维码连接
     */

    private final static String OPEN_QRCODE_URL = "https://open.weixin.qq.com/connect/qrconnect?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_login&state=%s#wechat_redirect";


    /**
     * 开放平台回调url
     * 注意：test16web.tunnel.qydev.com 域名地址要和在微信端 回调域名配置 地址一直，否则会报回调地址参数错误
     */

    private final static String OPEN_REDIRECT_URL = "http://www.huilvnet.com/callback";

    @RequestMapping("/callback")
    public void pay_notify(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter pw = null;
        System.out.println("支付完成进入异步通知");
        Map<String, String> paramsMap = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            paramsMap.put(name, valueStr);
        }
        log.info("------------#####################-------------paramsMap={}", paramsMap.toString());
        String outTradeNo = paramsMap.get("out_trade_no");
        String trade_status = paramsMap.get("trade_status");
        try {
            pw = response.getWriter();
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipayConfig.getPublicKey(), "UTF-8", "RSA2");
            //无论同步异步都要验证签名
            //if(signVerified){
            if ("TRADE_SUCCESS".equals(trade_status)) {
                log.info("------------#####################-------------1111111");
                MjOrder order = orderService.getOne(new LambdaQueryWrapper<MjOrder>().eq(MjOrder::getOrderCode, outTradeNo));
                if (order != null && order.getOrderStatus() == 0) {  //判断逻辑看业务场景
                    MjOrder upOrder = new MjOrder();
//                    upOrder.setOpenId(paramsMap.get("buyer_id"));
                    //videoOrder.setOutTradeNo(outTradeNo);
                    upOrder.setUpdateTime(new Date());
//                    upOrder.setPayTime(new Date());
//                    if("1".equals(upOrder.getProductType())){
//                        upOrder.setPayType("3");
//                    }else{
//                        upOrder.setPayType("0");
//                    }
//                    upOrder.setOrderStatus(1);
                    boolean flag = orderService.update(upOrder, new LambdaQueryWrapper<MjOrder>().eq(MjOrder::getOrderCode, outTradeNo));
                    //获取密钥逻辑------------------------
                    //根据订单号查询订单明细表，然后将订单明细得信息生成密钥
//                    List<MjOrderDetail> list = mjOrderDetailService.list(new LambdaQueryWrapper<MjOrderDetail>().eq(MjOrderDetail::getOrderCode, order.getOrderCode()));
//                    //循环获取密钥
//                    if (list != null && list.size() > 0) {
//                        for (int i = 0; i < list.size(); i++) {
//                            MjOrderDetail mjOrderDetail = list.get(i);
//                            MojiMiYaoDto mojiMiYaoDto = new MojiMiYaoDto();
//                            mojiMiYaoDto.setOrderId(mjOrderDetail.getOrderMxCode());
//                            mojiMiYaoDto.setRegion(mjOrderDetail.getServiceCityCode());
//                            mojiMiYaoDto.setType(mjOrderDetail.getCallWayCode());
//                            mojiMiYaoDto.setRate(mjOrderDetail.getCallCountCode());
//                            mojiMiYaoDto.setDuration(mjOrderDetail.getServiceTimeCode());
//                            //判断支付时间，如果支付时间在生效时间之后，以支付时间为准，如果支付时间在生效时间之前，以生效时间为准
//                            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//                            // 使用format方法转换Date到指定格式的字符串
//                            String formattedDate = sdf.format(mjOrderDetail.getEffectTime());
//                            mojiMiYaoDto.setValidStartTime(formattedDate);
//                            List<String> endpoints = new ArrayList<>();
//                            if (!TextUtils.isEmpty(mjOrderDetail.getWeatherTypeCode())) {
//                                String[] split = mjOrderDetail.getWeatherTypeCode().split("/");
//                                for (int j = 0; j < split.length; j++) {
//                                    endpoints.add(split[j]);
//                                }
//                            } else {
//                                String[] split = mjOrderDetail.getGlobalCityCode().split("/");
//                                for (int j = 0; j < split.length; j++) {
//                                    endpoints.add(split[j]);
//                                }
//                            }
//                            mojiMiYaoDto.setEndpoints(endpoints);
//                            // 创建Gson对象
//                            Gson gson = new Gson();
//                            // 将对象转换为JSON字符串
//                            String jsonString = gson.toJson(mojiMiYaoDto);
//                            log.info("------------#####################-------------支付宝调用墨迹"+jsonString, jsonString);
//                            String s = null;
//                            try {
//                                s = HttpUtils.sendPostRequest("/tob-data-misc/eshop/access/creation", jsonString);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                            log.info("------------#####################-------------支付宝调用墨迹vpn"+s, s);
//                            Gson gson1 = new Gson();
//                            MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s, MijiMoYaoVo1.class);
//                            if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
//                                log.info("------------#####################-------------支付宝调用墨迹成功1"+s, s);
//                                Gson gson2 = new Gson();
//                                MijiMoYaoVo mijiMoYaoVo = gson2.fromJson(s, MijiMoYaoVo.class);
//                                if (mijiMoYaoVo.getData().getAccess() != null && mijiMoYaoVo.getData().getAccess().getOrderId() != null) {
//                                    //核对订单号
//                                    if (mijiMoYaoVo.getData().getAccess().getOrderId().equals(mjOrderDetail.getOrderMxCode())) {
//                                        //将密钥更新到订单明细得springString2中
//                                        mjOrderDetail.setSpareString2(mijiMoYaoVo.getData().getAccess().getMdsPassword());
//                                        mjOrderDetail.setUpdateTime(new Date());
//                                        mjOrderDetail.setUseStatus(1);
//                                        mjOrderDetailService.updateById(mjOrderDetail);
//                                    }
//                                }
//                            }
//                            else{
//                                //获取墨迹密钥失败
//
//                            }
//
//
//                        }
//                    }
                    //结束---------------------------


                    if (flag) { //通知微信订单处理成功
                        pw.append("success");
                    } else {
                        pw.append("fail");
                    }
                } else {
                    pw.append("fail");
                }
            }
            //}else {
            //签名验证失败不处理业务逻辑
            //    pw.append("FAil");
            // }
        } catch (Exception e) {
            e.printStackTrace();
            pw.append("FAil");
        } finally {
            pw.flush();
            pw.close();
        }
    }
}

